import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class PageWithoutKeyPage extends StatefulWidget {
  const PageWithoutKeyPage({super.key});

  @override
  State<PageWithoutKeyPage> createState() => _PageWithoutKeyPageState();
}

class _PageWithoutKeyPageState extends State<PageWithoutKeyPage> {
  final GlobalKey _globalKey1 = GlobalKey();
  final GlobalKey _globalKey2 = GlobalKey();
  final GlobalKey _globalKey3 = GlobalKey();

  late List<Widget> list;

  @override
  void initState() {
    super.initState();
    list = [
      Box(
        color: Colors.red,
        key: _globalKey1,
      ),
      Box(
        color: Colors.yellow,
        key: _globalKey2,
      ),
      Box(
        color: Colors.blue,
        key: _globalKey3,
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    if (kDebugMode) {
      print(MediaQuery.of(context).orientation);
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text("PageWithoutKeyPage"),
      ),
      body: Center(
        child: MediaQuery.of(context).orientation == Orientation.portrait
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: list,
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: list,
              ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.refresh),
        onPressed: () {
          setState(() {
            list.shuffle(); // 排序打乱
          });
        },
      ),
    );
  }
}

class Box extends StatefulWidget {
  final Color color;

  const Box({super.key, required this.color});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 100,
      width: 100,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(widget.color),
        ),
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        child: Text(
          "$_count",
          style: Theme.of(context).textTheme.headlineLarge,
        ),
      ),
    );
  }
}
